package T6;

public class LinkedList implements IList{
    private Node head;//头节点

    @Override
    public void add(Object data) {
//        尾插法
        Node node = new Node(data);//创建一个node节点
        if (head == null){
           this.head = node;
        }else {
            Node cur = head;
            while(cur.next != null){
                cur = cur.next;
            }
            cur.next = node;
        }
    }

    @Override
    public boolean remove(Object data) {
//        删除data节点
       if (head == null){
           return false;
       }
//       如果头节点是要删除的数据
        if (head.data.equals(data)){
            head = head.next;
            return true;
        }
        Node cur = head;
        while(cur.next != null){
            if (cur.next.data.equals(data)){
//                找到要删除的节点
                cur.next = cur.next.next;
                return true;
            }
            cur = cur.next;
        }
        return false;  //遍历结束 没有找到
    }

    @Override
    public Node search(Object data) {
//        查找值为 data的节点
        Node cur = head;
        while(cur != null){
            if (cur.data.equals(data)){
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }

    @Override
    public boolean insertAfter(Node previous, Object data) {
//      在previous后插入data节点
        if (head == null) {
            return false;
        }
        Node cur = head;
        while(cur != null){
            if (cur == previous){
                Node newNOde = new Node(data);
                newNOde.next = cur.next;   //顺序不能变  先接后再连前
                cur.next = newNOde;
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    @Override
    public Node get(int index) {
//        找第index个节点
        if (index < 0 || index > size()){
//            索引无效异常
            throw new InvalidIndexException("Invalid index: "+ index);
        }
        Node cur = head;
        int count = 0;  //计数器
        while(cur != null){
            if (count == index){
                return cur;
            }
            cur = cur.next;
            count++;
        }
        // 如果循环结束还没有找到，表示索引超出链表长度
        throw new InvalidIndexException("Index out of bounds: " + index);
    }

    @Override
    public void set(Node node, Object data) {
//        将node引用节点的内容改成data
        if (node == null){
        } else {
            node.data = data;
        }
    }

    @Override
    public int size() {
//        链表长度
        int size = 0;
        if (head == null){
            return 0;
        }else {
            Node cur = head;
            while(cur != null){
                size++;
                cur = cur.next;
            }
        }
        return size;
    }
    public void  display(){
        Node cur = head;
        while(cur != null){
            System.out.print(cur.data +" ");
            cur = cur.next;
        }
        System.out.println();
    }
}
